<template>
  <el-dialog
    v-model="state.visible"
    fullscreen
    destroy-on-close
  >
    <div class="development-container" v-if="state.visible">
      <el-row class="jarmain" :style="{marginBottom:'10px'}">
        <el-col :span="23" class="jartitle">
          作业开发【{{ state.taskName }}】
        </el-col>
        <el-col :span="1" :style="{ textAlign: 'right', cursor: 'pointer' }">
          <div
            class="jartitle"
            @click="
              () =>
                RouterpushAndClosetag(this.$route, '/development/workManage')
            "
          >
          </div>
        </el-col>
      </el-row>
      <el-row class="development-ide-container" :gutter="20">
        <el-col class="ide-container-item" :span="3">
          <div class="tree-box">
            <!-- <data-source :source="source" @getCode="addCode"/> -->
          </div>
        </el-col>
        <el-col class="ide-container-item" :span="16">
          <MonacoEditor
            v-if="state.type == 'FlinkSQL'"
            ref="editorRef"
            :code="state.code"
            @getQuick="getQuick"
            @changeCode="changeCode"
          />
        </el-col>
        <el-col class="ide-container-item" :span="5">
          <div :class="state.type === 'FlinkSQL' ? 'sql-form configureBox' : 'jar-form configureBox'">
            <client
              ref="clientRef"
              :code="state.checkCode"
              :jar-id="state.jarId"
              :type="state.type"
              :task-params="state.taskParams"
              :chenge-form="state.chengeForm"
              @client="toClient"
            />
            <from-box
              :task-id="state.taskId"
              :type="state.type"
              @changeFrom="changeFrom"
              @getCode="getCode"
              @getJarName="getJarName"
            />
          </div>
        </el-col>
      </el-row>
      <el-row class="development-action-container">
        <CradPanels
          ref="cradPanelsRef"
          :cluster-id="state.clusterId"
          :run-info="state.runInfo"
          :task-params="state.taskParams"
          :task-data="state.taskData"
          :type="state.type"
          @changeTaskParams="changeTaskParams"
          @getCode="addCode"
          :taskId="state.taskId"
        />
      </el-row>

      <el-popover
        placement="top"
        width="300"
        v-model="state.partSqlVisible">
        <p>您已选中部分Sql语句, 是否只执行这些Sql语句？</p>
        <div style="text-align: right; margin: 0">
          <el-button size="mini" type="text" @click="cancelPartExecute">取消</el-button>
          <el-button type="primary" size="mini" @click="confirmPartExecute">确定</el-button>
        </div>
      </el-popover>
      <el-dialog title="提示" :visible="state.partSqlVisible" width="50%" :before-close="() => medium = false">
        <span>您已选中部分Sql语句, 是否只执行这些Sql语句？</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="state.dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="state.dialogVisible = false">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { nextTick, reactive, ref, toRefs, onActivated, defineEmits, onMounted,  } from "vue";
import { message, Modal } from 'ant-design-vue';
import MonacoEditor from './monacoEditor.vue'
import CradPanels from '../components/cardPanels.vue'
import client from '../components/client.vue'
import fromBox from '../components/fromBox.vue'
// import dataSource from '../components/dataSource.vue'
import { saveWork, executeSql, offlineWork, onlineWork, releaseWork, developWork, submitWork } from '../api/workDevelopment'
import moment from 'moment'
// import routeConfig from '@/views/common/mixins/routeConfig'
// import IconFont from '@/components/IconFont/index.vue'

// export default {
  // components: {
    // MonacoEditor,
    // CradPanels,
    // client,
    // fromBox,
    // IconFont,
    // dataSource
  // },
  // mixins: [routeConfig],

const state = reactive({
  visible: false,
  partSqlVisible: false,
  type: 'FlinkSQL',
  code: '',
  editor: null,
  activeName: 'first',
  treeData: [],
  defaultProps: {
    children: 'children',
    label: 'label'
  },

  reloadStatus: true,
  checkCode: '',

  jarId: '',
  // 暂时注释
  // jarFileName: null,
  taskParams: {},
  taskData: null,
  clusterId: 90,
  runInfo: null,
  chengeForm: false,
  source: 'task',
  id: '',
  taskId: '',
  taskName: '',
});

const init = (taskInfo:any) => {
  state.visible = true;
  state.id = taskInfo.id;
  state.taskId = taskInfo.id;
  state.taskName = taskInfo.jobName;
  state.initial = true
};
// 会话模式改变状态，回传改变后的任务参数
const changeTaskParams = (v:any) => {
  state.taskParams = v
};
const getJarName = (jarFileName:any) => {
  state.jarFileName = jarFileName
};
const uploadSuccess = (jarId:any) => {
  state.taskParams.jarId = jarId
  state.jarId = jarId
};
const uploadFailure = (res:any) => {
  notifyFailure(res.message || res.msg)
};
const removedFile = () => {
  state.taskParams.jarId = null
};
const toClient = (type:any) => {
  // 获取编辑器内容
  if (type === 'add_to_drive') {
    saveFrom({
      ...state.taskParams,
      session: '',
      jobName: state.taskParams.name,
      useSession: false,
      useRemote: true,
      mainClass: ' ',
      paras: ' '
    })
  } else if (type === 'play_circle') {
    executeHandle()
  } else if (type === 'pause_circle') {
    // 暂停
    offLineOrPauseTask('canceljob')
  } else if (type === 'mode_edit') {
    // 修改
    developTask()
  } else if (type === 'assignment_turned_in') {
    // 发布
    release()
  } else if (type === 'airplane_ticket') {
    // 异步提交
    taskSubmit()
  } else if (type === 'work_online') {
    // 作业上线
    workOnline()
  } else if (type === 'work_offline') {
    // 作业下线
    offLineOrPauseTask('cancel')
  }
};
// 保存按钮
const editorRef = ref();
const saveFrom = async (param:any) => {
  state.isLoading = true;
  param.statement = editorRef.value.getCodeContext()
  param.configJson = JSON.stringify(param.config)
  param.alertGroupId = param.alertGroupId === true ? 1 : param.alertGroupId === false ? 0 : null
  param.taskId = state.taskId
  await saveWork(param)
    .then((res) => {
      if (res.indexOf('成功') !== -1) {
        state.chengeForm = false
        notifySuccess(res)
      } else {
        notifyFailure(res)
      }
    })
    .finally(() => {
      state.loading = false
      state.isLoading = false
    })
};
// 作业上线
const workOnline = () => {
  onlineWork({
    id: state.taskId
  }).then((res) => {
    if (res) {
      state.taskParams.step = 5
      notifySuccess(res)
    }
  })
  .finally(() => {
    state.loading = false
    state.isLoading = false
  })
};
const executeHandle = () => {
  let highlightSql = editorRef.value.getSelection()
  console.log(highlightSql);
  let sql = editorRef.value.getCodeContext()
  if(highlightSql) {
    Modal.confirm({
      title: '提示',
      content: '您已选中部分Sql语句, 是否只执行这些Sql语句？',
      onOk() {
        excuteSql(highlightSql);
      },
      onCancel() {
        excuteSql(sql);
      },
    });
    return;
  }
  excuteSql(sql);
};
const cancelPartExecute = () => {
  state.partSqlVisible = false;
  let sql = editorRef.value.getCodeContext()
  excuteSql(sql);
};
const confirmPartExecute = () => {
  state.partSqlVisible = false;
};
// 执行sql
const cradPanelsRef = ref()
const excuteSql = (sql:any) => {
  // 执行、运行
  const param = state.taskParams
  state.isLoading = true
  if ((param.type === 'standalone' || param.type === 'yarn-session') && param.clusterId == null) {
    notifyFailure('请选择Flink集群')
    return
  }
  if ((param.type === 'yarn-per-job' || param.type === 'yarn-application') && param.clusterConfigurationId == null) {
    notifyFailure('请选择Flink集群')
    return
  }
  if (state.chengeForm) {
    notifyFailure('表单有修改，请保存后再执行!')
    state.isLoading = false
    return
  }
  param.statement = sql;
  param.jobName = state.taskParams.name
  param.taskId = state.taskParams.id
  param.useRemote = true
  param.taskId = state.taskId
  executeSql(param)
    .then((res) => {
      if (res.code && res.code === 1001) {
        res.data.startTime = res.data.startTime ? moment(res.data.startTime).format('YYYY-MM-DD HH:mm:ss') : ''
        res.data.endTime = res.data.endTime ? moment(res.data.endTime).format('YYYY-MM-DD HH:mm:ss') : ''
        state.runInfo = res.data
        notifyFailure(res.msg || res.message)
      } else {
        res.startTime = res.startTime ? moment(res.startTime).format('YYYY-MM-DD HH:mm:ss') : ''
        res.endTime = res.endTime ? moment(res.endTime).format('YYYY-MM-DD HH:mm:ss') : ''
        state.runInfo = res
        state.taskParams.jobInstanceId = res.jobInstanceId
        notifySuccess('执行成功！')
        cradPanelsRef.value.implementProcess()
      }
    })
    .finally((res) => {
      state.loading = false
      state.isLoading = false
    })
};
// 作业停止对应运行
const offLineOrPauseTask = (type:any) => {
  state.isLoading = true
  offlineWork({
    id: state.taskId,
    type
  })
    .then((res) => {
      if (res) {
        state.taskParams.jobInstanceId = 0
        if (type === 'cancel') {
          state.taskParams.step = 4
        }
        notifySuccess(res.msg || res.message)
      }
    })
    .finally(() => {
      state.loading = false
      state.isLoading = false
    })
};
// 作业发布
const release = () => {
  state.isLoading = true
  releaseWork({ id: state.taskId })
    .then((res) => {
      if (res) {
        state.taskParams.step = 4
        notifySuccess('操作成功！')
      }
    })
    .finally(() => {
      state.loading = false
      state.isLoading = false
    })
};
// 作业开发
const developTask = () => {
  state.isLoading = true
  developWork({ id: state.taskId })
    .then((res) => {
      if (res) {
        state.taskParams.step = 2
        notifySuccess('操作成功！')
      }
    })
    .finally(() => {
      state.loading = false
      state.isLoading = false
    })
};
// 作业提交
const taskSubmit = () => {
  state.isLoading = true
  submitWork({ id: state.taskId })
    .then((res) => {
      if (res && res.jobInstanceId) {
        state.taskParams.jobInstanceId = res.jobInstanceId
        notifySuccess('操作成功！')
      } else {
        notifyFailure('提交失败！')
        state.loading = false
        state.isLoading = false
        return
      }
    })
    .finally(() => {
      state.loading = false
      state.isLoading = false
    })
};
const changeFrom = (param:any, taskData:any) => {
  state.isLoading = false
  delete param.updateTime
  state.taskParams = param
  if (state.initial) {
    state.chengeForm = false
    console.log('刚开始')
  } else {
    state.chengeForm = true
    console.log('改变form状态')
  }
  state.taskParams.taskId = state.taskId
  state.jarId = param.jarId
  state.clusterId = param.clusterId
  state.taskData = taskData
  console.log('水水水水水', state.taskData)
};
const getCode = (code:any) => {
  state.code = code
  state.checkCode = code
};
const addCode = (code:any) => {
  state.code = editorRef.value.getCodeContext() + code
  state.checkCode = editorRef.value.getCodeContext() + code
  state.chengeForm = true
};
const changeCode = (code:any) => {
  state.checkCode = code
  state.chengeForm = true
};
const clientRef = ref()
const getQuick = (str:any) => {
  // console.log(str);
  switch (str) {
    case 'Ctrl + S':
      saveFrom(state.taskParams)
      break
    case 'Alt+2':
      clientRef.value.checkSql()
      break
    case 'Alt+3':
      console.log('美化')
      break
    default:
      console.log('其他')
  }
};
const notifySuccess = (text:any) => {
  message.success(text);
};
const notifyFailure = (text:any) => {
  message.error(text);
}

defineExpose({
  init
});

</script>

<style lang="scss" scoped>
.development-container{
  width: 100%;
  height: calc(100vh - 160px);
  .development-ide-container{
    width: 100%;
    height: 70%;
    .ide-container-item{
      height: 100%;
      .configureBox {
        width: 100%;
        height: 100%;
        // overflow: auto;
      }
      .tree-box{
        width: 100%;
        height: 100%;
        overflow: scroll;
      }
    }
  }
  .development-action-container{
    width: 100%;
       height: 30%;
    overflow: hidden;
  }
}

</style>

